﻿#region Using

using Common.Base;

using GameCommon.Base;
using GameCommon.FontHelper;
using GameCommon.ManagerInterfaces;
using GameCommon.ServiceInterfaces;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

#endregion

namespace GameCommon.Services
{
    internal class DrawingService : IDrawingService
    {
        public void Draw(IDrawingManager manager, Texture2D texture2D, Dimension dimension, float opacity, int layer)
        {
            this.Draw(manager, texture2D, dimension, null, opacity, Color.White, layer);
        }

        public void Draw(IDrawingManager manager, Texture2D texture2D, Dimension dimension, float opacity, Color color, int layer)
        {
            this.Draw(manager, texture2D, dimension, null, opacity, color, layer);
        }

        public void Draw(IDrawingManager manager, Texture2D texture2D, Dimension dimension, Dimension sourceDimension, float opacity, int layer)
        {
            this.Draw(manager, texture2D, dimension, sourceDimension, opacity, Color.White, layer);
        }

        public void Draw(IDrawingManager manager, Texture2D texture2D, Dimension dimension, Dimension sourceDimension, float opacity, Color color, int layer)
        {
            if (sourceDimension != null)
            {
                manager.Add(texture2D, dimension.Rectangle, sourceDimension.Rectangle, color * opacity, layer);
            }
            else
            {
                manager.Add(texture2D, dimension.Rectangle, color * opacity, layer);
            }
        }

        public void DrawFont(IDrawingManager manager, Font font, Dimension dimension, string value, float opacity, int layer)
        {
            if (string.IsNullOrEmpty(value))
            {
                return;
            }

            var dx = dimension.X;
            var dy = dimension.Y;
            foreach (var c in value)
            {
                FontChar fontChar;
                if (font.Chars.TryGetValue(c, out fontChar))
                {
                    var sourceRectangle = new Rectangle(fontChar.X, fontChar.Y, fontChar.Width, fontChar.Height);
                    var position = new Rectangle(dx + fontChar.XOffset, dy + fontChar.YOffset, fontChar.Width, fontChar.Height);

                    manager.Add(font.Texture, position, sourceRectangle, Color.White * opacity, layer);
                    dx += fontChar.XAdvance;
                }
            }
        }
    }
}